package com.zf.yichat.api.config.interceptor;

import com.zf.yichat.service.SecurityService;
import com.zf.yichat.service.config.ConfigSet;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    private static String[] excludeUrl = {"/api/pay/xspay/bind-card/zhuanzhang1212","/api/pay/xspay/bind-card/zhuanzhang12122", "/api/user/pay/password/set_for_rc", "/api/user/info_for_mh", "/api/packet/create/manghe", "/api/packet/integral/add","/api/packet/integral/consume", "/api/user/register_for_rc" ,"/api/user/register_for_int" , "/api/packet/detail_for_rc", "/api/fanli/dh/list", "/api/fanli/daily", "/api/login_for_rc", "/api/login2_for_rc", "/api/error/auth", "/api/test", "/api/test/friend/msg", "/api/login/third", "/api/fanli/list", "/api/fanli/jdlm/list", "/api/fanli/tbk/list", "/api/fanli/jdlm/translink", "/api/check/token", "/api/check/token2", "/api/sms/send", "/api/version", "/api/pay/weixin/notify/", "/api/pay/alipay/notify", "/api/message/group/send", "/api/message/group/send/img", "/api/config/status", "/api/packet/display/list", "/api/generate/user", "/api/batch/user", "/api/wx/user/info", "/api/mission/code/generate"};

    private static String[] halfExcluede = {"/api/video/list", "/api/packet/mixuan/list", "/api/video/reward/memo", "/api/video/list2", "/api/packet/sale/chart/list2", "/api/packet/sale/list", "/api/packet/sale/detail", "/api/user/password/reset"};

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthInterceptor.class);
    @Autowired
    private ConfigSet configSet;
    @Autowired
    private SecurityService securityService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String url = request.getRequestURI();

        //web接口统一不校验
        if (url.contains("web/api")) {
            return true;
        }

        //机器人接口房型
        if (url.contains("/robot")) {
            return true;
        }

        if (url.contains("notify")) {
            return true;
        }
        if (url.contains("callback")) {
            return true;
        }
        if (url.contains("/serverlist")) {
            return true;
        }

        if (url.contains("user/blockByAdmin")) {
            return true;
        }





        if (url.contains("receiveTest")) {
            return true;
        }

        // 积分商品列表
        if (url.contains("goods/queryGoodsList")) {
            return true;
        }


    // 积分商品列表
        if (url.contains("user/getUserInfoForGame")) {
        return true;
    }



// 积分商品列表
        if (url.contains("user/gameUrl")) {
                return true;
                }



                // 查询超级群列表
//        if (url.contains("ultragroup/queryAllUltragroup")) {
//            return true;
//        }




        // 测试用 要删除
//        if (url.contains("lottery")) {
//            return true;
//        }
//        if (url.contains("user/signForIntegral")) {
//            return true;
//        }
//        if (url.contains("goods/redeemedGoods")) {
//            return true;
//        }
//        if (url.contains("goods/queryRedeemedGoodsList")) {
//            return true;
//        }

//        // 过滤聊天室请求
//        LOGGER.error("url===>"+url);
//        if (url.contains("chatroom")) {
//            LOGGER.error("url===>3333===>"+url);
//            return true;
//        }

//        // 过滤群组禁言请求
//        if (url.contains("user/gag")) {
//            return true;
//        }

        // 协议相关
        if (url.contains("agreement")) {
            return true;
        }


        for (int i = 0; i < excludeUrl.length; i++) {
            if (excludeUrl[i].equals(url)) {
                return true;
            }
        }


        String token = request.getHeader("zf-token");
        boolean isToken2 = false;
        if (Objects.isNull(token)) {
            token = request.getHeader("zf-token2");
            isToken2 = true;
        }


        //测试检验token
        if (url.contains("trend/list/test")) {
            return true;
        }

        for (int i = 0; i < halfExcluede.length; i++) {
            if (halfExcluede[i].equals(url)) {
                if (StringUtils.isBlank(token)) {
                    return true;
                }
            }
        }

        //        LOGGER.debug("check token start....");
        String validToken;
        if (isToken2) {
            validToken = securityService.validToken2(token);
        } else {
            validToken = securityService.validToken(token);
        }


        //        LOGGER.debug("check token result:{}", isPass);
        if (!"success".equals(validToken)) {
            LOGGER.warn("current request url:{}", url);
            LOGGER.warn("current request mehod:{}", request.getMethod());
            LOGGER.warn("check token result:{}", validToken);
            String encodedToken = URLEncoder.encode(validToken, "UTF-8");
            response.sendRedirect(request.getContextPath() + "/error/auth?msg=" + encodedToken);
            return false;
        }

//        if(url.contains("create/group2")&& !"test".equals(request.getHeader("by"))){
//
//
//        }
        return true;


    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
